<template>
  <Page class="book-view">
    <template #header>
      <div class="content-header" style="display: flex; justify-content: space-between; align-items: center">
        <!-- 左侧的面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>全部书籍</el-breadcrumb-item>
          <el-breadcrumb-item>待发布</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </template>
    <el-table
      class="tableContainer"
      size="small"
      current-row-key="id"
      :data="bookList"
      stripe
      highlight-current-row
      cell-class-name="book_cell"
    >
      <el-table-column type="index" label="序号" width="50" />
      <el-table-column prop="book_image" label="书本图片">
        <template v-slot="scope">
          <el-image class="book-img" :src="getBookImageUrl(scope.row.book_image)" style="width: 60px; height: auto">
            <template #error>
              <div class="img-fallback">
                <el-icon><Notebook /></el-icon>
                <div class="img-fallback-text">Cover</div>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="书名" />
      <el-table-column prop="price" label="价格" width="60" />
      <el-table-column prop="number" label="库存数量" width="80" />
      <el-table-column prop="isbn" label="ISBN号" />
      <el-table-column label="作者国籍" :formatter="formatNationality">
        <template v-slot="scope">{{ formatNationality(scope.row.author_nationality) }}</template>
      </el-table-column>

      <el-table-column prop="create_time" label="创建时间" />
      <el-table-column prop="update_time" label="更新时间" />
      <el-table-column label="操作" align="center" width="300">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button
            :type="scope.row.hasPublish ? 'info' : 'success'"
            size="small"
            @click="handlePublish(scope.row.id)"
            class="publish-button"
            :class="{ 'has-commented': scope.row.hasPublish }"
          >
            <span class="button-text">{{ scope.row.hasPublish ? '已发布' : '发布' }}</span>
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      size="small"
      class="pagination"
      @current-change="handleCurrentChange"
      :current-page="pageData.currentPage"
      :page-size="pageData.pageSize"
      layout="total, prev, pager, next, jumper"
      :total="pageData.total"
    >
    </el-pagination>
  </Page>
  <book-dialog v-model="bookForm" v-model:visible="dialogFormVisible" @ok="onOK" :type="dialogType" />
  <purchase-dialog v-model:visible8="dialogFormVisible8" v-model:transaction-id="transactionId" />
</template>

<script setup lang="ts">
import Page from '@/components/Page.vue';
import { http } from '@/services/http';
import type { Book, PageData, ResponseData } from '@/types';
import { API_ROOT, BookType, Nationality } from '@/types/constant';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import type { BookDialogType } from './BookDialog.vue';
import BookDialog from './BookDialog.vue';
import PurchaseDialog from './PurchaseDialog.vue';
import { useUserStore } from '@/stores/user';
import { useRoute, useRouter } from 'vue-router';
import router from '@/router';
import { getBookImageUrl } from '@/utils';

const originBookForm: Book = {
  owner: 0,
  book_code: '',
  name: '',
  isbn: '',
  number: 0,
  author_nationality: Nationality.Chinese,
  book_image: '',
  applicable_scope: '',
  type: BookType.Textbook,
  price: 0,
  description: '',
  notes: '',
};
const transactionId = ref(0);
const imgUrl = ref('');
const bookForm = reactive<Book>({ ...originBookForm });
const dialogFormVisible = ref(false);
const bookList = ref<Book[]>([]);
const userStore = useUserStore();
const pageData = reactive({
  //分页相关模型数据
  owner: userStore.userInfo.id,
  nationality: '',
  currentPage: 1, // 当前页码
  pageSize: 10, // 每页显示的记录数
  total: 60, // 总记录数
  queryString: '', // 查询条件
});
const dialogType = ref<BookDialogType>('Create');
const dialogFormVisible8 = ref(false);
const handleDelete = (id: number) => {
  ElMessageBox.confirm('此操作将永久删除该书目, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      http.get<ResponseData>('/books/del', { id: id }).then((ResponseData) => {
        ElMessage({ type: 'success', message: ResponseData.msg });
        getBookListByPage();
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      });
    });
  getBookListByPage();
};

const handleEdit = () => {
  http.post<ResponseData>('/books/update', bookForm).then((res) => {
    if (res.flag) {
      ElMessage({ type: 'success', message: res.msg });
      pageData.currentPage = 1;
      getBookListByPage();
      dialogFormVisible.value = false;
    } else {
      ElMessage({ type: 'error', message: res.msg || '编辑失败' });
    }
  });
};
const onOK = () => {
  if (dialogType.value == 'Create') {
    handleAdd();
  } else {
    handleEdit();
  }
};

const handleAdd = () => {
  bookForm.owner = userStore.userInfo.id;
  http.post<ResponseData>('/books/create', bookForm).then((res) => {
    if (res.flag) {
      ElMessage({ type: 'success', message: res.msg });
      getBookListByPage();
      dialogFormVisible.value = false;
    } else {
      ElMessage({ type: 'error', message: res.msg || '添加失败' });
    }
  });
};

const handlePublish = (id: number) => {
  ElMessageBox.confirm('确定发布?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const param1 = {
        id: id,
        owner: userStore.userInfo.id,
      };
      http.post<ResponseData>('/books/hasPublish', param1).then((ResponseData) => {
        ElMessage({ type: 'success', message: ResponseData.msg });
        getBookListByPage();
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消发布',
      });
    });
  getBookListByPage();
};

const handleUpdate = (book: Book) => {
  dialogType.value = 'Edit';
  dialogFormVisible.value = true;
  Object.assign(bookForm, book);
  const newImgUrl = ref(getBookImageUrl(book.book_image));
  imgUrl.value = newImgUrl.value;
};

const handleCurrentChange = (u: number) => {
  pageData.currentPage = u;
  getBookListByPage();
};

const getBookListByPage = () => {
  http.post<ResponseData<PageData>>('/books/publish', pageData).then((res) => {
    bookList.value = res.data.list;
    pageData.total = res.data.total;
  });
};
const formatNationality = (nationalityCode: any) => {
  switch (nationalityCode) {
    case Nationality.Chinese:
      return '中国';
    case Nationality.ForeignChinese:
      return '外籍华人';
    case Nationality.Foreign:
      return '外籍';
    default:
      return nationalityCode;
  }
};

const findOwner = () => {
  http.post<ResponseData<PageData>>('/books/findOwner', pageData).then((res) => {
    bookList.value = res.data.list;
    pageData.total = res.data.total;
    pageData.queryString = '';
    pageData.nationality = '';
  });
};

const getPublishedBooks = () => {
  http.post<ResponseData<PageData>>('/books/published', pageData).then((res) => {
    bookList.value = res.data.list;
    pageData.total = res.data.total;
    pageData.queryString = '';
    pageData.nationality = '';
  });
};
const route = useRoute();
onMounted(() => {
  const ownerId = Number(route.params.ownerId);
  const type = route.params.type;
  console.log(11, ownerId);
  console.log(22, type);

  if (ownerId) {
    pageData.owner = Number(ownerId);

    if (type === 'all') {
      findOwner();
    } else if (type === 'published') {
      getPublishedBooks();
    }
  } else {
    getBookListByPage();
  }
});
</script>

<style>
.book_cell {
  margin-top: 10px;
}
.filter-container {
  display: flex;
  margin: 16px 0;
}
.filter-item {
  width: 200px;
  margin-right: 12px;
}
.pagination {
  margin-top: 10px;
  margin-bottom: 10px;
}
.el-image {
  display: inline-flex;
}
.book-img {
  display: flex;
}
.img-fallback {
  width: 50px;
  height: 70px;
  box-shadow: 0 0 2px #333;
  margin: 5px;
  padding: 2px 0 0 5px;
  .img-fallback-text {
    font-weight: 900;
    color: #fe8738;
  }
}

.avatar-container {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}
</style>
